
<template>
    <div class="category-management system">
      <header class="app-header">
        <h1 class="page-title">课程分类管理</h1>
      </header>
  
      <div class="main-container">
        <!-- 左侧树形面板 -->
        <aside class="category-sidebar">
          <div class="panel-header">
            <h2>分类目录</h2>
            <el-button type="text" icon="Plus" @click="openAddRootDialog">新建根分类</el-button>
          </div>
          
          <div class="scroll-container">
            <el-tree
              :data="categoryTree"
              node-key="id"
              :props="defaultProps"
              default-expand-all
              :render-content="renderCategoryNode"
              class="category-tree"
              @node-click="handleNodeClick"
              :highlight-current="true"
            />
          </div>
        </aside>
  
        <!-- 右侧详情面板 -->
        <main class="category-main">
          <div v-if="currentCategory" class="detail-container">
            <div class="detail-header">
              <div class="header-content">
                <h2>{{ currentCategory.categoryName }}</h2>
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.id">
                    {{ item.categoryName }}
                  </el-breadcrumb-item>
                </el-breadcrumb>
              </div>
              
              <div class="action-group">
                <el-button type="primary" @click="openAddChildDialog">
                  <el-icon><Plus /></el-icon> 添加子分类
                </el-button>
                <el-button @click="openEditDialog">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-popconfirm
                  title="确定删除该分类及其所有子分类？"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-warning"
                  icon-color="#f56c6c"
                  @confirm="handleDelete"
                >
                  <template #reference>
                    <el-button type="danger" icon="Delete">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
  
            <el-form class="detail-form" :model="currentCategory" label-width="140px">
              <el-form-item label="分类ID" prop="id" disabled>
                <el-input v-model="currentCategory.id" :disabled="true" />
              </el-form-item>
              <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="currentCategory.categoryName" placeholder="请输入分类名称" />
              </el-form-item>
              <el-form-item label="父级分类" prop="parentCategoryId">
                <el-select v-model="currentCategory.parentCategoryId" placeholder="请选择父级分类">
                  <el-option
                    v-for="item in availableParents"
                    :key="item.id"
                    :label="item.categoryName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </main>
      </div>
  
      <!-- 新建分类对话框 -->
      <el-dialog
        v-model="addDialogVisible"
        :title="isAddRoot ? '新建根分类' : '新建子分类'"
        class="dialog-window"
        :before-close="handleCloseDialog"
      >
        <el-form :model="newCategory" :rules="categoryRules" ref="addFormRef">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="newCategory.categoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item v-if="!isAddRoot" label="父级分类" prop="parentCategoryId">
            <el-select v-model="newCategory.parentCategoryId" placeholder="请选择父级分类">
              <el-option
                v-for="item in availableParents"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-actions">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddCategory" :loading="submitLoading">
              确认创建
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { 
    Plus, Edit
  } from '@element-plus/icons-vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import categoryHttp from '@/http/http.js';
  
  // API配置
  const api = {
    getCategories: () => categoryHttp.get('/lzs/courseCategory'),
    addCategory: (form) => categoryHttp.post('/lzs/courseCategory', form),
    updateCategory: (form) => categoryHttp.put(`/lzs/courseCategory}`, form),
    deleteCategory: (id) => categoryHttp.delete(`/lzs/courseCategory/${id}`)
  };

  // 状态管理
  const categoryTree = ref([]);
  const currentCategory = ref({});
  const newCategory = reactive({
    categoryName: '',
    parentCategoryId: null
  });
  const addDialogVisible = ref(false);
  const isAddRoot = ref(true);
  const submitLoading = ref(false);
  const currentEditingId = ref(null);

  // 表单引用
  const addFormRef = ref(null);
  const consultantId = ref('');
  // 获取登录咨询师的 ID
onMounted(()=>{
  consultantId.value = JSON.parse(sessionStorage.getItem("consultant")).id;
  console.log(consultantId.value,"11111111111111111111111111111111111111111");

})

  // 计算属性
  const defaultProps = {
    children: 'children',
    label: 'categoryName'
  };

  const availableParents = computed(() => {
    if (!currentCategory.value.id) return [];
    return categoryTree.value.filter(c =>
      c.id !== currentCategory.value.id &&
      !c.children.some(child => child.id === currentCategory.value.id)
    );
  });

  // 生命周期
  onMounted(async () => {
    try {
      await loadCategories();
    } catch (error) {
      handleError(error);
    }
  });

  // API请求方法
  const loadCategories = async () => {
    try {
      const response = await api.getCategories();
      categoryTree.value = buildCategoryTree(response.data.list);

      
    

      if (categoryTree.value.length) {
        currentCategory.value = categoryTree.value[0];
      }
    } catch (error) {
      handleError(error);
    }
  };

  // 树形结构转换（关键修复）
  const buildCategoryTree = (list) => {
    const map = {};
    const tree = [];

    // 使用字符串键存储节点
    list.forEach(item => {
      map[item.id.toString()] = {
        ...item,
        children: [],
        label: item.categoryName // 确保显示字段正确
      };
    });

    // 构建树结构
    list.forEach(item => {
      const node = map[item.id.toString()];
      if (item.parentCategoryId) {
        const parent = map[item.parentCategoryId.toString()];
        if (parent) parent.children.push(node);
      } else {
        tree.push(node);
      }
    });

    return tree;
  };

  // 节点渲染（修复显示问题）
  const renderCategoryNode = (h, { node, data }) => {
    return h(
      'span',
      {
        class: 'custom-tree-node',
        onClick: (e) => {
          e.stopPropagation();
          handleNodeClick(data);
        }
      },
      [
        h('span', { class: 'tree-label' }, [
          h('i', { class: 'el-icon-folder' }),
          h('span', node.label)
        ]),
        h('span', { class: 'tree-operations' }, [
          h('el-button', {
            props: { type: 'text', size: 'mini' },
            on: {
              click: (e) => {
                e.stopPropagation();
                openEditDialog(data);
              }
            }
          }, [
            h('i', { class: 'el-icon-edit' }, '编辑')
          ])
        ])
      ]
    );
  };

  // 节点点击处理
  const handleNodeClick = (category) => {
    currentCategory.value = category;
  };

  // 添加分类
  const openAddChildDialog = () => {
    isAddRoot.value = false;
    newCategory.parentCategoryId = currentCategory.value.id;
    newCategory.categoryName = '';
    addDialogVisible.value = true;
  };

  const handleAddCategory = async () => {
    try {
      await addFormRef.value.validate();
      const formData = {
        ...newCategory,
        parentCategoryId: newCategory.parentCategoryId
      };

      await api.addCategory(formData);
      await loadCategories();
      ElMessage.success('添加成功');
      addDialogVisible.value = false;
    } catch (error) {
      handleError(error);
    }
  };
  
  // 编辑分类
  const openEditDialog = (category) => {
    currentEditingId.value = category.id;
    newCategory.categoryName = category.categoryName;
    newCategory.parentCategoryId = category.parentCategoryId;
    addDialogVisible.value = true;
  };
  
  // 删除分类
  const handleDelete = async () => {
    try {
      await ElMessageBox.confirm('确定删除该分类及其所有子分类？', '确认删除');
      await api.deleteCategory(currentCategory.value.id);
      await loadCategories();
      ElMessage.success('删除成功');
    } catch (error) {
      handleError(error);
    }
  };
  
  // 错误处理
  const handleError = (error) => {
    console.error('API Error:', error);
    ElMessage.error(error.message || '操作失败，请稍后重试');
  };
  </script>
  
  <style scoped>
  /* 全局样式重置 */
  body {
    margin: 0;
    padding: 0;
    overflow: hidden; /* 阻止全局滚动 */
  }
  
  /* 主体布局 */
  .main-container {
    display: flex;
    height: calc(100vh - 64px); /* 减去header高度 */
    overflow: hidden; /* 阻止容器滚动 */
  }
  
  /* 左侧树形面板 */
  .category-sidebar {
    width: 300px;
    background: #f8f9fa;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .scroll-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px 0;
  }
  
  /* 树节点样式优化 */
  .custom-tree-node {
    padding: 8px 16px;
    transition: all 0.2s ease;
    border-radius: 4px;
  }
  
  .custom-tree-node:hover {
    background: #ebf5ff;
    cursor: pointer;
  }
  
  .tree-label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
  }
  
  .tree-operations {
    opacity: 0;
    transition: opacity 0.3s;
    margin-left: auto;
  }
  
  .custom-tree-node:hover .tree-operations {
    opacity: 1;
  }
  
  /* 右侧详情面板 */
  .category-main {
   
    flex: 1;
    overflow-y: auto;
    padding: 24px;
  }
  
  .detail-container {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .header-content {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  
  .breadcrumb {
    margin-top: 4px;
    font-size: 12px;
    color: #909399;
  }
  
  .action-group {
    display: flex;
    gap: 10px;
  }
  
  /* 表单样式优化 */
  .detail-form {
    max-width: 600px;
  }
  
  .el-form-item {
    margin-bottom: 24px;
  }
  
  /* 对话框样式 */
  .dialog-window {
    width: 500px;
    border-radius: 8px;
  }
  
  .dialog-actions {
    display: flex;
    gap: 10px;
  }
  
  /* 头部样式 */
  .app-header {
    padding: 0 24px;
    height: 64px;
    line-height: 64px;
    background: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    position: sticky;
    top: 0;
    z-index: 100;
  }
  
  /* 悬停状态增强 */
  .el-tree-node__content:hover {
    background-color: #f0f7ff;
  }
  
  /* 面包屑样式 */
  .breadcrumb /deep/ .el-breadcrumb__inner {
    color: #606266;
  }
  
  .breadcrumb /deep/ .el-breadcrumb__inner a:hover {
    color: #409eff;
  }
  </style>